"""
添加各大赛区的知名战队到数据库
"""
import os
import requests
import shutil
from app import create_app
from app.models.models import db, Team

# 战队数据，包含名称、联赛、游戏和图标URL - 使用更可靠的图片链接
TEAMS_DATA = [
    # LCK
    {
        "name": "T1",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/8HMvI1v.png"
    },
    {
        "name": "Gen.G",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/R6cPDM1.png"
    },
    {
        "name": "DRX",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/u3KoCVh.png"
    },
    {
        "name": "Hanwha Life Esports",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/XFX9Iil.png"
    },
    {
        "name": "KT Rolster",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/lHhfyU9.png"
    },
    {
        "name": "DWG KIA",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/4LHvLvv.png"
    },
    {
        "name": "Kwangdong Freecs",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/QMoGXR0.png"
    },
    {
        "name": "Liiv SANDBOX",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/DvN1DMT.png"
    },
    {
        "name": "Nongshim RedForce",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/1RwswKH.png"
    },
    {
        "name": "OK BRION",
        "league": "LCK",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/Bv3tDwu.png"
    },

    # LPL
    {
        "name": "JD Gaming",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/1QEA0h9.png"
    },
    {
        "name": "Top Esports",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/PbOj5W8.png"
    },
    {
        "name": "Bilibili Gaming",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/9d5lKKJ.png"
    },
    {
        "name": "LNG Esports",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/cQBOFIy.png"
    },
    {
        "name": "EDward Gaming",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/NnzgG4C.png"
    },
    {
        "name": "RNG",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/Q3VbQIh.png"
    },
    {
        "name": "FPX",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/TlkVIlQ.png"
    },
    {
        "name": "Weibo Gaming",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/VT7hiDS.png"
    },
    {
        "name": "WE",
        "league": "LPL",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/0WaLVV9.png"
    },
    {
        "name": "OMG",
        "league": "LPL",
        "game": "英雄联盟", 
        "icon_url": "https://i.imgur.com/lMVJOEG.png"
    },

    # LEC
    {
        "name": "G2 Esports",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/xJqUEiW.png"
    },
    {
        "name": "Fnatic",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/YsOnD7I.png"
    },
    {
        "name": "MAD Lions",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/WxdQcMN.png"
    },
    {
        "name": "Rogue",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/kqcm5QV.png"
    },
    {
        "name": "Team Vitality",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/DHnZ8nZ.png"
    },
    {
        "name": "Excel Esports",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/iXFU0ZO.png"
    },
    {
        "name": "SK Gaming",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/nVwWVVR.png"
    },
    {
        "name": "Astralis",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/lTggC6B.png"
    },
    {
        "name": "Team BDS",
        "league": "LEC",
        "game": "英雄联盟",
        "icon_url": "https://i.imgur.com/eOjJHGA.png"
    }
]

def download_image(url, save_path):
    """
    下载图片并保存到指定路径
    """
    try:
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                response.raw.decode_content = True
                shutil.copyfileobj(response.raw, f)
            return True
        else:
            print(f"下载失败 {url}: 状态码 {response.status_code}")
            return False
    except Exception as e:
        print(f"下载异常 {url}: {e}")
        return False

def add_teams_to_db():
    """
    添加战队到数据库
    """
    app = create_app()
    with app.app_context():
        # 创建图标目录
        icons_dir = os.path.join(app.static_folder, 'team_icons')
        os.makedirs(icons_dir, exist_ok=True)
        
        # 复制默认图标如果不存在
        default_icon_path = os.path.join(icons_dir, 'default_team.png')
        if not os.path.exists(default_icon_path):
            # 创建一个简单的默认图标文件
            with open(default_icon_path, 'wb') as f:
                # 简单的灰色PNG图片数据
                f.write(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00d\x00\x00\x00d\x08\x02\x00\x00\x00\xff\x80\x02\x03\x00\x00\x00\x19IDATX\x85\xed\xc1\x01\x01\x00\x00\x00\x82 \xff\xafnH@\x01\x00\x00\x00\x00\x00\x00\x00\x00\xf0\r\x07\x0c\x00\x01\x9d\x1d\xd9\xec\x00\x00\x00\x00IEND\xaeB`\x82')
                print("创建了默认图标文件")
        
        teams_added = 0
        # 遍历战队数据并添加到数据库
        for team_data in TEAMS_DATA:
            # 检查战队是否已存在
            existing_team = Team.query.filter_by(name=team_data['name']).first()
            if existing_team:
                print(f"战队 {team_data['name']} 已存在")
                continue
                
            # 下载图标
            icon_filename = f"{team_data['name'].lower().replace(' ', '_').replace('.', '').replace('-', '_')}.png"
            icon_path = os.path.join(icons_dir, icon_filename)
            
            if download_image(team_data['icon_url'], icon_path):
                print(f"图标下载成功: {team_data['name']}")
            else:
                print(f"图标下载失败: {team_data['name']}, 使用默认图标")
                icon_filename = 'default_team.png'
            
            # 创建新战队
            new_team = Team(
                name=team_data['name'],
                league=team_data['league'],
                game=team_data['game'],
                icon=icon_filename,
                total_matches=0,
                wins=0
            )
            
            # 添加到数据库
            db.session.add(new_team)
            teams_added += 1
        
        # 提交事务
        db.session.commit()
        print(f"战队数据添加完成，共添加 {teams_added} 支战队")

if __name__ == "__main__":
    add_teams_to_db() 